package com.ittx.dzt.ali.health.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.ittx.dzt.ali.health.factory.TbSdkClientFactory;
import com.ittx.dzt.ali.health.handler.AbstractBaseAliHealthApiHandler;
import com.ittx.dzt.edi.constant.GeneralConstant;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.log.monitor.ExceptionLog;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.sys.util.json.JacksonTool;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAlihealthShiporderConfirmRequest;
import com.taobao.api.response.AlibabaAlihealthShiporderConfirmResponse;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import open.dto.ShipmentDispatchDto;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 直发发货单确认
 * <p>
 * cy.shipment.dispatch
 * alibaba.alihealth.shiporder.confirm
 * https://open.taobao.com/api.htm?docId=37527&docType=2
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/3/19
 */
@Slf4j
@Service
public class AliHealthShipOrderConfirmService extends AbstractBaseAliHealthApiHandler<ShipmentDispatchDto> {
	@Override
	public String getLocalApiMethod() {
		return PlatformApiConstant.InboundInterface.SHIPMENT_DISPATCH;
	}

	@Override
	public Result<?> doProcess(PlatformApiParamDTO platformApiParamDTO, ShipmentDispatchDto dto) {
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		AlibabaAlihealthShiporderConfirmResponse rsp = null;
		try {
			TaobaoClient client = TbSdkClientFactory.getTaobaoClient(storeConfig.getSdkUrl(), storeConfig.getAppKey(), storeConfig.getAppSecret());
			AlibabaAlihealthShiporderConfirmRequest req = new AlibabaAlihealthShiporderConfirmRequest();
			//	运单号
			req.setLpOrderCode(dto.getWaybillCode());
			// 发货单id
			req.setMainShipOrderId(dto.getSourceOrderCode());
			// 快递公司编码
			req.setLogisticProviderCode(dto.getCarrierCode());
			List<AlibabaAlihealthShiporderConfirmRequest.ZfScmShipOrderConfirmItemDTO> shipOrderConfirmItemDTOS = Lists.newArrayList();
			//	多包裹详情
			Optional.ofNullable(dto.getPacks())
					.ifPresent(packs -> packs.forEach(pack -> {
						AlibabaAlihealthShiporderConfirmRequest.ZfScmShipOrderConfirmItemDTO itemDTO = new AlibabaAlihealthShiporderConfirmRequest.ZfScmShipOrderConfirmItemDTO();
						itemDTO.setLpOrderCode(pack.getWaybillCode());
						itemDTO.setShipCountMap(pack.getShipCountMap());
						itemDTO.setLogisticProviderCode(pack.getCarrierCode());
						shipOrderConfirmItemDTOS.add(itemDTO);
					}));
			if (CollUtil.isNotEmpty(shipOrderConfirmItemDTOS) && !Objects.equals(GeneralConstant.YesOrNo.YES, dto.getIsAll())) {
				req.setZfScmShipOrderConfirmItemDto(shipOrderConfirmItemDTOS);
			}
			// 批次效期信息
			List<AlibabaAlihealthShiporderConfirmRequest.ZfScmShipOrderItemBatchDTO> itemBatchDTOList = Lists.newArrayList();
			Optional.ofNullable(dto.getAliHealthBatchItemParameters())
					.ifPresent(batchItems -> batchItems.forEach(item -> {
						AlibabaAlihealthShiporderConfirmRequest.ZfScmShipOrderItemBatchDTO itemBatchDTO = new AlibabaAlihealthShiporderConfirmRequest.ZfScmShipOrderItemBatchDTO();
						itemBatchDTO.setProduceDate(item.getProduceDate());
						itemBatchDTO.setAmount(item.getAmount());
						itemBatchDTO.setAcceptor(item.getAcceptor());
						if (StrUtil.isNotEmpty(item.getOrderItemId())) {
							itemBatchDTO.setOrderItemId(Long.valueOf(item.getOrderItemId()));
						}
						itemBatchDTO.setDueDate(item.getDueDate());
						itemBatchDTO.setBatchCode(item.getBatchCode());
						itemBatchDTO.setBarCode(item.getBarCode());
						itemBatchDTOList.add(itemBatchDTO);
					}));
			if (CollUtil.isNotEmpty(itemBatchDTOList)) {
				req.setZfScmShipOrderItemBatchDto(itemBatchDTOList);
			}
			log.debug("入参数据：{} 请求参数:{}", JacksonTool.toJson(dto), JacksonTool.toJson(req));
			rsp = client.execute(req, storeConfig.getSessionKey());
			log.debug("响应数据：{}", JacksonTool.toJson(rsp));
			if (!rsp.isSuccess() || !rsp.getResult().getSuccess()) {
				String logStr = StrUtil.format("ErrorCode:{},Msg:{},SubCode:{},subMsg:{},rsp:{}", rsp.getErrorCode(), rsp.getMsg()
						, rsp.getSubCode(), rsp.getSubMsg(),JacksonTool.toJson(rsp));
				log.error(PlatformMessageConstant.MSG_PLAT_0003_MSG, platformApiParamDTO.getRequestId(), this.getPlatformCode(), platformApiParamDTO.getApi(), logStr);
				return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, platformApiParamDTO.getRequestId(),
						this.getPlatformCode(), platformApiParamDTO.getApi(), logStr))).addMsg(rsp.getSubMsg());
			}
			return Result.success(rsp.getResult());
		} catch (Exception e) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, platformApiParamDTO.getRequestId(), this.getPlatformCode(), platformApiParamDTO.getApi(), e.getMessage());
			ExceptionLog.error(e, msg);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg));
		}
	}
}
